package com.greenyoung.pwiki.markdown.controller;

import com.github.pagehelper.PageInfo;

import com.greenyoung.pwiki.markdown.entity.Markdown;
import com.greenyoung.pwiki.markdown.entity.Msg;
import com.greenyoung.pwiki.markdown.mapper.MarkdownMapper;
import com.greenyoung.pwiki.markdown.service.MarkdownService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@RestController
public class MarkdownController {
    @Autowired
    MarkdownMapper markdownMapper;

    @Autowired
    MarkdownService markdownService;

    @PostMapping("/com/greenyoung/pwiki/markdown")
//    public Msg handleFileUpload(@RequestParam(value = "file",required = false) MultipartFile file,
//                                RedirectAttributes redirectAttributes) {

    public Msg handleFileUpload(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            markdownService.saveFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
        return Msg.success();
    }

    @GetMapping("/com/greenyoung/pwiki/markdown/{id}")
    public Markdown getMarkdown(@PathVariable("id") Long id) {
        return markdownMapper.selectByPrimaryKey(id);
    }

    /**
     * 通过路由分页查询markdown数据
     * /markdowns/1/10: 每页10个数据，返回第一页结果，每页大小不能超过20
     * /markdowns/1: 默认页大小为5
     *
     * @param pageNum
     * @return
     */
    @GetMapping("/markdowns/{pn}/{ps}")
    public Msg getMarkdowns(@PathVariable(value = "pn", required = true) Integer pageNum,
                            @PathVariable(value = "ps") Integer pageSize) {
        if (pageSize == null) {
            pageSize = 5;
        }
        if (pageSize > 20) {
            return Msg.fail().setMsg("Page size too large!");
        }
        try {
            PageInfo pageInfo = markdownService.getMarkdownsByPageNum(pageNum,pageSize);
            return Msg.success().add("pageInfo", pageInfo);
        } catch (Exception e) {
            return Msg.fail();
        }
    }

    @GetMapping("/markdownc/{id}")
    public Msg getMarkdownContent(@PathVariable(value = "id") Long id){
        try {
           String markdownContent=markdownService.getMarkdownContentById(id);
           return Msg.success().add("content",markdownContent);
        }catch (Exception e){
            return Msg.fail();
        }
    }
}